package cmd

import (
	"context"
	"device-admin/config/redis"
	"fmt"
	"log"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/cobra"
)

// 修复数据的类型
var fixDataType string

func init() {
	rootCmd.PersistentFlags().StringVarP(&fixDataType, "type", "t", "", "fix db data")
	rootCmd.AddCommand(fixDBDataCmd)
}

// 支持的数据处理类型  类型名 => 处理函数
var FixDBFunc = map[string]func(arg []string){
	"delRedisKeys":    delRedisKeys,
	"expireRedisKeys": expireRedisKeys,
}

// 数据库数据临时修复脚本
var fixDBDataCmd = &cobra.Command{
	Use:   "fixdb",
	Short: "fixdb",
	Run: func(c *cobra.Command, arg []string) {
		startTime := time.Now()
		if _, ok := FixDBFunc[fixDataType]; ok {
			FixDBFunc[fixDataType](arg)
		} else {
			fmt.Println("未知的类型")
		}
		usedTime := time.Since(startTime)
		fmt.Println("输入参数arg:", "fixdb -t", fixDataType, strings.Join(arg, " "))
		fmt.Println("修复数据全程耗时:", usedTime)
	},
}

// delRedisKeys 批量删除redis key
func delRedisKeys(args []string) {
	if len(args) != 1 {
		panic("请输入key!")
	}
	rdb := redis.NewDB()
	var keys []string
	var cursor uint64
	for {
		keys, cursor, _ = rdb.Scan(context.Background(), cursor, args[0], 1000).Result()
		for _, key := range keys {
			rdb.Del(context.Background(), key)
		}
		log.Printf("本次删除%d个\n", len(keys))
		time.Sleep(time.Millisecond * 100)
		if cursor == 0 {
			break
		}
	}
}

// expireRedisKeys 重新设置redis key的过期时间
func expireRedisKeys(args []string) {
	if len(args) != 2 {
		panic("请输入key和过期时间")
	}
	expireSecond, _ := strconv.Atoi(args[1])
	rdb := redis.NewDB()
	var keys []string
	var cursor uint64
	for {
		keys, cursor, _ = rdb.Scan(context.Background(), cursor, args[0], 1000).Result()
		for _, key := range keys {
			rdb.Expire(context.Background(), key, time.Second*time.Duration(expireSecond))
		}
		time.Sleep(time.Millisecond * 100)
		if cursor == 0 {
			break
		}
	}
}
